<template>
  <div class="turnover-analysis-container">
    <el-row :gutter="20">
      <el-col :span="24">
        <el-card class="filter-card">
          <template #header>
            <div class="card-header">
              <h3>库存周转分析</h3>
              <div>
                <el-button type="primary" @click="generateAnalysis">生成分析</el-button>
                <el-button type="success" @click="exportData">导出报表</el-button>
              </div>
            </div>
          </template>
          
          <!-- 筛选条件 -->
          <el-form :inline="true" :model="filterForm" class="filter-form">
            <el-form-item label="分析日期">
              <el-date-picker
                v-model="filterForm.dateRange"
                type="daterange"
                range-separator="至"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
                format="YYYY-MM-DD"
                value-format="YYYY-MM-DD"
              />
            </el-form-item>
            <el-form-item label="仓库">
              <el-select v-model="filterForm.warehouseId" placeholder="请选择仓库" clearable>
                <el-option 
                  v-for="warehouse in warehouses" 
                  :key="warehouse.id" 
                  :label="warehouse.name" 
                  :value="warehouse.id" 
                />
              </el-select>
            </el-form-item>
            <el-form-item label="物料类型">
              <el-select v-model="filterForm.materialType" placeholder="请选择物料类型" clearable>
                <el-option label="原材料" value="raw" />
                <el-option label="半成品" value="semi" />
                <el-option label="成品" value="finished" />
                <el-option label="包装材料" value="packaging" />
              </el-select>
            </el-form-item>
            <el-form-item label="周转率分组">
              <el-select v-model="filterForm.turnoverGroup" placeholder="请选择分组方式">
                <el-option label="按物料类型" value="type" />
                <el-option label="按仓库" value="warehouse" />
                <el-option label="按物料分类" value="category" />
                <el-option label="按供应商" value="supplier" />
              </el-select>
            </el-form-item>
          </el-form>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 总体周转指标 -->
    <el-row :gutter="20" class="dashboard-row">
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-value">{{ metrics.overallTurnover.toFixed(2) }}</div>
          <div class="metric-title">整体周转率</div>
          <div class="metric-subtitle">
            较上期
            <span :class="metrics.overallTrend > 0 ? 'trend-up' : 'trend-down'">
              {{ metrics.overallTrend > 0 ? '+' : '' }}{{ metrics.overallTrend }}%
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-value">{{ metrics.turnoverDays }} 天</div>
          <div class="metric-title">平均周转天数</div>
          <div class="metric-subtitle">
            较上期
            <span :class="metrics.daysTrend > 0 ? 'trend-down' : 'trend-up'">
              {{ metrics.daysTrend > 0 ? '+' : '' }}{{ metrics.daysTrend }}%
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-value">{{ metrics.inventoryValue }}万</div>
          <div class="metric-title">平均库存价值</div>
          <div class="metric-subtitle">
            较上期
            <span :class="metrics.valueTrend > 0 ? 'trend-down' : 'trend-up'">
              {{ metrics.valueTrend > 0 ? '+' : '' }}{{ metrics.valueTrend }}%
            </span>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="metric-card">
          <div class="metric-value">{{ metrics.lowTurnoverRate }}%</div>
          <div class="metric-title">低周转物料占比</div>
          <div class="metric-subtitle">
            较上期
            <span :class="metrics.lowTurnoverTrend > 0 ? 'trend-down' : 'trend-up'">
              {{ metrics.lowTurnoverTrend > 0 ? '+' : '' }}{{ metrics.lowTurnoverTrend }}%
            </span>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 周转分析图表 -->
    <el-row :gutter="20" class="chart-row">
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h4>物料类型周转率对比</h4>
            </div>
          </template>
          <div class="chart-container-wrapper">
            <div id="materialTypeChart" class="chart-container"></div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="12">
        <el-card class="chart-card">
          <template #header>
            <div class="card-header">
              <h4>月度周转率趋势</h4>
            </div>
          </template>
          <div class="chart-container-wrapper">
            <div id="monthlyTrendChart" class="chart-container"></div>
          </div>
        </el-card>
      </el-col>
    </el-row>
    
    <!-- 周转率列表 -->
    <el-row>
      <el-col :span="24">
        <el-card class="list-card">
          <template #header>
            <div class="card-header">
              <h4>物料周转详情</h4>
              <el-radio-group v-model="viewMode" size="small">
                <el-radio-button value="table" label="表格视图"></el-radio-button>
                <el-radio-button value="card" label="卡片视图"></el-radio-button>
              </el-radio-group>
            </div>
          </template>
          
          <!-- 表格视图 -->
          <div v-if="viewMode === 'table'">
            <el-table
              :data="turnoverList"
              border
              style="width: 100%"
              v-loading="loading"
            >
              <el-table-column prop="materialCode" label="物料编码" width="120" sortable />
              <el-table-column prop="materialName" label="物料名称" width="180" />
              <el-table-column prop="materialType" label="物料类型" width="100">
                <template #default="scope">
                  <el-tag>{{ getMaterialTypeLabel(scope.row.materialType) }}</el-tag>
                </template>
              </el-table-column>
              <el-table-column prop="warehouseName" label="仓库" width="120" />
              <el-table-column prop="averageInventory" label="平均库存" width="100" sortable />
              <el-table-column prop="consumptionAmount" label="消耗量" width="100" sortable />
              <el-table-column prop="turnoverRate" label="周转率" sortable>
                <template #default="scope">
                  <span :class="getTurnoverRateClass(scope.row.turnoverRate)">
                    {{ scope.row.turnoverRate.toFixed(2) }}
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="turnoverDays" label="周转天数" sortable>
                <template #default="scope">
                  <span :class="getTurnoverDaysClass(scope.row.turnoverDays)">
                    {{ scope.row.turnoverDays }} 天
                  </span>
                </template>
              </el-table-column>
              <el-table-column prop="inventoryValue" label="库存价值" sortable>
                <template #default="scope">
                  ¥{{ formatCurrency(scope.row.inventoryValue) }}
                </template>
              </el-table-column>
              <el-table-column prop="trend" label="趋势" width="100">
                <template #default="scope">
                  <el-tag :type="scope.row.trend > 0 ? 'success' : 'danger'">
                    {{ scope.row.trend > 0 ? '上升' : '下降' }} {{ Math.abs(scope.row.trend) }}%
                  </el-tag>
                </template>
              </el-table-column>
            </el-table>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[10, 20, 50, 100]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
          
          <!-- 卡片视图 -->
          <div v-else class="card-view">
            <el-row :gutter="20">
              <el-col :span="8" v-for="item in turnoverList" :key="item.id">
                <el-card class="turnover-item-card" shadow="hover">
                  <div class="turnover-item-header">
                    <div class="item-name">{{ item.materialName }}</div>
                    <div class="item-code">{{ item.materialCode }}</div>
                  </div>
                  <div class="turnover-item-body">
                    <div class="item-rate">
                      <span class="label">周转率:</span>
                      <span :class="getTurnoverRateClass(item.turnoverRate)">
                        {{ item.turnoverRate.toFixed(2) }}
                      </span>
                    </div>
                    <div class="item-days">
                      <span class="label">周转天数:</span>
                      <span :class="getTurnoverDaysClass(item.turnoverDays)">
                        {{ item.turnoverDays }} 天
                      </span>
                    </div>
                    <div class="item-warehouse">
                      <span class="label">仓库:</span>
                      <span>{{ item.warehouseName }}</span>
                    </div>
                    <div class="item-inventory">
                      <span class="label">平均库存:</span>
                      <span>{{ item.averageInventory }}</span>
                    </div>
                    <div class="item-value">
                      <span class="label">库存价值:</span>
                      <span>¥{{ formatCurrency(item.inventoryValue) }}</span>
                    </div>
                  </div>
                  <div class="turnover-item-footer">
                    <el-tag :type="item.trend > 0 ? 'success' : 'danger'" size="small">
                      {{ item.trend > 0 ? '上升' : '下降' }} {{ Math.abs(item.trend) }}%
                    </el-tag>
                  </div>
                </el-card>
              </el-col>
            </el-row>
            
            <!-- 分页 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="pagination.currentPage"
                v-model:page-size="pagination.pageSize"
                :page-sizes="[9, 18, 36]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="pagination.total"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
              />
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { ref, reactive, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { ElMessage } from 'element-plus'
import * as echarts from 'echarts'
import { useChart } from '../../../utils/chartUtils'

export default {
  name: 'TurnoverAnalysis',
  setup() {
    // 状态变量
    const loading = ref(false)
    const viewMode = ref('table')
    
    // 图表实例
    const { 
      initChart: initMaterialTypeChart, 
      updateChart: updateMaterialTypeChart, 
      disposeChart: disposeMaterialTypeChart 
    } = useChart('materialTypeChart', 'materialTypeChart')
    
    const { 
      initChart: initMonthlyTrendChart, 
      updateChart: updateMonthlyTrendChart, 
      disposeChart: disposeMonthlyTrendChart 
    } = useChart('monthlyTrendChart', 'monthlyTrendChart')
    
    // 仓库数据
    const warehouses = ref([
      { id: 'WH001', name: '中央仓库' },
      { id: 'WH002', name: '北区配送中心' },
      { id: 'WH003', name: '南方仓储中心' },
      { id: 'WH004', name: '西部物流中心' }
    ])
    
    // 过滤表单
    const filterForm = reactive({
      dateRange: ['2024-01-01', '2024-06-30'],
      warehouseId: '',
      materialType: '',
      turnoverGroup: 'type'
    })
    
    // 分页数据
    const pagination = reactive({
      currentPage: 1,
      pageSize: 10,
      total: 0
    })
    
    // 总体指标
    const metrics = reactive({
      overallTurnover: 5.2,
      turnoverDays: 42,
      inventoryValue: 380.5,
      lowTurnoverRate: 18,
      overallTrend: 8,
      daysTrend: -5,
      valueTrend: 3,
      lowTurnoverTrend: -2
    })
    
    // 周转列表
    const turnoverList = ref([])
    
    // 加载周转数据
    const loadTurnoverData = () => {
      loading.value = true
      
      // 模拟API调用
      setTimeout(() => {
        // 生成模拟周转数据
        turnoverList.value = [
          {
            id: 'T001',
            materialCode: 'RAW10001',
            materialName: '铝合金型材',
            materialType: 'raw',
            warehouseId: 'WH001',
            warehouseName: '中央仓库',
            averageInventory: 850,
            consumptionAmount: 2550,
            turnoverRate: 3.0,
            turnoverDays: 60,
            inventoryValue: 68000,
            trend: 5
          },
          {
            id: 'T002',
            materialCode: 'SEMI20045',
            materialName: '电路组件A',
            materialType: 'semi',
            warehouseId: 'WH001',
            warehouseName: '中央仓库',
            averageInventory: 300,
            consumptionAmount: 1800,
            turnoverRate: 6.0,
            turnoverDays: 30,
            inventoryValue: 45000,
            trend: 12
          },
          {
            id: 'T003',
            materialCode: 'FIN30012',
            materialName: '智能控制器V2',
            materialType: 'finished',
            warehouseId: 'WH002',
            warehouseName: '北区配送中心',
            averageInventory: 120,
            consumptionAmount: 960,
            turnoverRate: 8.0,
            turnoverDays: 23,
            inventoryValue: 96000,
            trend: 15
          },
          {
            id: 'T004',
            materialCode: 'PKG40056',
            materialName: '高档包装盒',
            materialType: 'packaging',
            warehouseId: 'WH001',
            warehouseName: '中央仓库',
            averageInventory: 1500,
            consumptionAmount: 3000,
            turnoverRate: 2.0,
            turnoverDays: 90,
            inventoryValue: 37500,
            trend: -8
          },
          {
            id: 'T005',
            materialCode: 'RAW50023',
            materialName: '钢化玻璃面板',
            materialType: 'raw',
            warehouseId: 'WH003',
            warehouseName: '南方仓储中心',
            averageInventory: 500,
            consumptionAmount: 1750,
            turnoverRate: 3.5,
            turnoverDays: 52,
            inventoryValue: 40000,
            trend: -3
          }
        ]
        
        // 更新总数
        pagination.total = 58
        
        loading.value = false
        
        // 刷新图表数据
        refreshCharts()
      }, 500)
    }
    
    // 初始化图表
    const initCharts = async () => {
      try {
        await nextTick()
        await initMaterialTypeChart()
        await initMonthlyTrendChart()
        refreshCharts()
      } catch (error) {
        console.error('初始化图表失败:', error)
      }
    }
    
    // 刷新图表数据
    const refreshCharts = () => {
      // 更新物料类型周转率对比图表
      updateMaterialTypeChart(getMaterialTypeChartOption())
      
      // 更新月度周转率趋势图表
      updateMonthlyTrendChart(getMonthlyTrendChartOption())
    }
    
    // 获取物料类型周转率对比图表选项
    const getMaterialTypeChartOption = () => {
      return {
        tooltip: {
          trigger: 'axis',
          axisPointer: {
            type: 'shadow'
          }
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '3%',
          containLabel: true
        },
        xAxis: {
          type: 'value',
          name: '周转率'
        },
        yAxis: {
          type: 'category',
          data: ['原材料', '半成品', '成品', '包装材料'],
          axisLabel: {
            fontSize: 14
          }
        },
        series: [
          {
            name: '周转率',
            type: 'bar',
            data: [
              {value: 3.5, itemStyle: {color: '#409EFF'}},
              {value: 6.0, itemStyle: {color: '#67C23A'}},
              {value: 8.0, itemStyle: {color: '#E6A23C'}},
              {value: 2.0, itemStyle: {color: '#F56C6C'}}
            ],
            label: {
              show: true,
              position: 'right',
              fontSize: 14
            }
          }
        ]
      }
    }
    
    // 获取月度周转率趋势图表选项
    const getMonthlyTrendChartOption = () => {
      return {
        tooltip: {
          trigger: 'axis'
        },
        grid: {
          left: '3%',
          right: '4%',
          bottom: '3%',
          top: '8%',
          containLabel: true
        },
        xAxis: {
          type: 'category',
          data: ['1月', '2月', '3月', '4月', '5月', '6月']
        },
        yAxis: {
          type: 'value',
          name: '周转率',
          axisLabel: {
            formatter: '{value}'
          }
        },
        series: [
          {
            name: '周转率',
            type: 'bar',
            data: [3.2, 4.8, 4.2, 5.8, 5.2, 6.0],
            itemStyle: {
              color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                { offset: 0, color: '#83bff6' },
                { offset: 0.5, color: '#188df0' },
                { offset: 1, color: '#188df0' }
              ])
            },
            emphasis: {
              itemStyle: {
                color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [
                  { offset: 0, color: '#2378f7' },
                  { offset: 0.7, color: '#2378f7' },
                  { offset: 1, color: '#83bff6' }
                ])
              }
            }
          }
        ]
      }
    }
    
    // 生成分析
    const generateAnalysis = () => {
      loading.value = true
      
      // 模拟API调用
      setTimeout(() => {
        ElMessage.success('周转分析已生成')
        loadTurnoverData()
      }, 1000)
    }
    
    // 导出报表
    const exportData = () => {
      ElMessage.success('周转分析报表已导出')
    }
    
    // 格式化货币
    const formatCurrency = (value) => {
      return parseFloat(value).toLocaleString('zh-CN', {
        minimumFractionDigits: 2,
        maximumFractionDigits: 2
      })
    }
    
    // 获取物料类型标签
    const getMaterialTypeLabel = (type) => {
      switch (type) {
        case 'raw':
          return '原材料'
        case 'semi':
          return '半成品'
        case 'finished':
          return '成品'
        case 'packaging':
          return '包装材料'
        default:
          return '未知'
      }
    }
    
    // 获取周转率CSS类
    const getTurnoverRateClass = (rate) => {
      if (rate >= 8) return 'rate-excellent'
      if (rate >= 4) return 'rate-good'
      if (rate >= 2) return 'rate-normal'
      return 'rate-low'
    }
    
    // 获取周转天数CSS类
    const getTurnoverDaysClass = (days) => {
      if (days <= 30) return 'days-excellent'
      if (days <= 60) return 'days-good'
      if (days <= 90) return 'days-normal'
      return 'days-slow'
    }
    
    // 处理页码变更
    const handleCurrentChange = (val) => {
      pagination.currentPage = val
      loadTurnoverData()
    }
    
    // 处理每页条数变更
    const handleSizeChange = (val) => {
      pagination.pageSize = val
      loadTurnoverData()
    }
    
    // 页面加载时获取数据
    onMounted(() => {
      loadTurnoverData()
      initCharts()
    })
    
    // 组件卸载前销毁图表实例
    onBeforeUnmount(() => {
      disposeMaterialTypeChart()
      disposeMonthlyTrendChart()
    })
    
    return {
      loading,
      viewMode,
      warehouses,
      filterForm,
      turnoverList,
      pagination,
      metrics,
      
      generateAnalysis,
      exportData,
      formatCurrency,
      getMaterialTypeLabel,
      getTurnoverRateClass,
      getTurnoverDaysClass,
      handleCurrentChange,
      handleSizeChange
    }
  }
}
</script>

<style>
.turnover-analysis-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.filter-form {
  display: flex;
  flex-wrap: wrap;
}

.filter-card {
  margin-bottom: 20px;
}

.dashboard-row {
  margin-bottom: 20px;
}

.metric-card {
  height: 120px;
  text-align: center;
  display: flex;
  flex-direction: column;
  justify-content: center;
}

.metric-value {
  font-size: 28px;
  font-weight: bold;
  color: #303133;
  margin-bottom: 5px;
}

.metric-title {
  font-size: 14px;
  color: #606266;
  margin-bottom: 10px;
}

.metric-subtitle {
  font-size: 12px;
  color: #909399;
}

.trend-up {
  color: #67C23A;
}

.trend-down {
  color: #F56C6C;
}

.chart-row {
  margin-bottom: 20px;
}

.chart-card {
  height: 350px;
  display: flex;
  flex-direction: column;
}

.chart-card .el-card__body {
  flex: 1;
  padding: 0;
  display: flex;
  flex-direction: column;
}

.chart-container-wrapper {
  position: relative;
  flex: 1;
  min-height: 0;
  padding: 10px;
}

.chart-container {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}

.list-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: center;
}

.rate-excellent {
  color: #67C23A;
  font-weight: bold;
}

.rate-good {
  color: #409EFF;
  font-weight: bold;
}

.rate-normal {
  color: #E6A23C;
}

.rate-low {
  color: #F56C6C;
}

.days-excellent {
  color: #67C23A;
  font-weight: bold;
}

.days-good {
  color: #409EFF;
  font-weight: bold;
}

.days-normal {
  color: #E6A23C;
}

.days-slow {
  color: #F56C6C;
}

.card-view {
  margin-top: 20px;
}

.turnover-item-card {
  margin-bottom: 20px;
}

.turnover-item-header {
  margin-bottom: 10px;
}

.item-name {
  font-weight: bold;
  font-size: 16px;
  margin-bottom: 5px;
}

.item-code {
  color: #909399;
  font-size: 12px;
}

.turnover-item-body {
  margin-bottom: 15px;
}

.turnover-item-body > div {
  margin-bottom: 5px;
}

.label {
  color: #606266;
  margin-right: 5px;
}

.turnover-item-footer {
  text-align: right;
}

/* 确保下拉框宽度为180px */
.el-select {
  width: 180px !important;
}

/* 特殊情况下需要100%宽度的select */
.full-width-select .el-select {
  width: 100% !important;
}

@media (max-width: 1200px) {
  .chart-card {
    height: 300px;
  }
}

@media (max-width: 768px) {
  .chart-card {
    height: 250px;
  }
}

@media (max-width: 480px) {
  .chart-card {
    height: 200px;
  }
}
</style> 